import React, { useState, useEffect } from 'react';
import { Outlet, Link, useNavigate, useLocation } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import { logout } from '@/redux/slices/authSlice';
import { RootState } from '@/redux/store';
import { 
  HomeOutlined, 
  BookOutlined, 
  CheckSquareOutlined,
  LogoutOutlined
} from '@ant-design/icons';
import '@/styles/layouts/mainLayout.scss';

const MainLayout: React.FC = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const { teacher } = useSelector((state: RootState) => state.auth);
  const [activeItem, setActiveItem] = useState('');

  useEffect(() => {
    // 根据当前路径设置活动菜单项
    const path = location.pathname;
    if (path === '/' || path.startsWith('/dashboard')) {
      setActiveItem('dashboard');
    } else if (path.startsWith('/courses')) {
      setActiveItem('courses');
    } else if (path.startsWith('/sign-in')) {
      setActiveItem('signIn');
    }
  }, [location]);

  const handleLogout = () => {
    if (window.confirm('确定要退出登录吗？')) {
      dispatch(logout());
      navigate('/login');
    }
  };

  return (
    <div className="main-layout">
      <header className="header">
        <div className="logo">智慧课堂教师端</div>
        <div className="user-info">
          <span>欢迎，{teacher?.name || '教师'}</span>
          <button className="logout-btn" onClick={handleLogout}>
            <LogoutOutlined /> 退出登录
          </button>
        </div>
      </header>
      
      <div className="container">
        <aside className="sidebar">
          <nav className="nav-menu">
            <ul>
              <li className={activeItem === 'dashboard' ? 'active' : ''}>
                <Link to="/dashboard">
                  <HomeOutlined /> <span>首页</span>
                </Link>
              </li>
              <li className={activeItem === 'courses' ? 'active' : ''}>
                <Link to="/courses">
                  <BookOutlined /> <span>课程管理</span>
                </Link>
              </li>
              <li className={activeItem === 'signIn' ? 'active' : ''}>
                <Link to="/sign-in">
                  <CheckSquareOutlined /> <span>签到管理</span>
                </Link>
              </li>
            </ul>
          </nav>
        </aside>
        
        <main className="content">
          <Outlet />
        </main>
      </div>
      
      <footer className="footer">
        <p>&copy; 2025 智慧课堂教师端 版权所有</p>
      </footer>
    </div>
  );
};

export default MainLayout; 